package com.css.zfzx.sjcj.modules.hddcRock25Pre.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.repository.HddcRock25preNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.repository.HddcRock25preRepository;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.repository.entity.HddcRock25preEntity;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.service.HddcRock25preService;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.viewobjects.HddcRock25preQueryParams;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.viewobjects.HddcRock25preVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-27
 */
@Service
public class HddcRock25preServiceImpl implements HddcRock25preService {

	@Autowired
    private HddcRock25preRepository hddcRock25preRepository;
    @Autowired
    private HddcRock25preNativeRepository hddcRock25preNativeRepository;

    @Override
    public JSONObject queryHddcRock25pres(HddcRock25preQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcRock25preEntity> hddcRock25prePage = this.hddcRock25preNativeRepository.queryHddcRock25pres(queryParams, curPage, pageSize, sort, order);
        List<HddcRock25preVO> hddcRock25preVOList = new ArrayList<>();
        List<HddcRock25preEntity> hddcRock25preEntityList = hddcRock25prePage.getContent();
        for(HddcRock25preEntity hddcRock25preEntity : hddcRock25preEntityList){
            HddcRock25preVO hddcRock25preVO = new HddcRock25preVO();
            BeanUtils.copyProperties(hddcRock25preEntity, hddcRock25preVO);
            if(PlatformObjectUtils.isNotEmpty(hddcRock25preEntity.getSymbol())) {
                String dictItemCode=String.valueOf(hddcRock25preEntity.getSymbol());
                hddcRock25preVO.setSymbolName(findByDictCodeAndDictItemCode("RockTypeCVD", dictItemCode));
            }
            hddcRock25preVOList.add(hddcRock25preVO);
        }
        Page<HddcRock25preVO> HddcRock25preVOPage = new PageImpl(hddcRock25preVOList, hddcRock25prePage.getPageable(), hddcRock25prePage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(HddcRock25preVOPage);
        return jsonObject;
    }


    @Override
    public HddcRock25preEntity getHddcRock25pre(String id) {
        HddcRock25preEntity hddcRock25pre = this.hddcRock25preRepository.findById(id).orElse(null);
         return hddcRock25pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock25preEntity saveHddcRock25pre(HddcRock25preEntity hddcRock25pre) {
        String uuid = UUIDGenerator.getUUID();
        hddcRock25pre.setUuid(uuid);
        hddcRock25pre.setCreateUser(PlatformSessionUtils.getUserId());
        hddcRock25pre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcRock25pre.setIsValid("1");
        hddcRock25pre.setQualityinspectionStatus("0");
        hddcRock25pre.setExtends10("1");
        this.hddcRock25preRepository.save(hddcRock25pre);
        return hddcRock25pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcRock25preEntity> saveHddcRock25preList(List<HddcRock25preEntity> list) {
        for (HddcRock25preEntity hddcRock25pre : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcRock25pre.setUuid(uuid);
            hddcRock25pre.setCreateUser(PlatformSessionUtils.getUserId());
            hddcRock25pre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcRock25pre.setIsValid("1");
            hddcRock25pre.setQualityinspectionStatus("0");
            hddcRock25pre.setExtends10("1");
        }

        return hddcRock25preNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock25preEntity updateHddcRock25pre(HddcRock25preEntity hddcRock25pre) {
        HddcRock25preEntity entity = hddcRock25preRepository.findById(hddcRock25pre.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcRock25pre);
        hddcRock25pre.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRock25pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRock25preRepository.save(hddcRock25pre);
        return hddcRock25pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRock25pres(List<String> ids) {
        List<HddcRock25preEntity> hddcRock25preList = this.hddcRock25preRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcRock25preList) && hddcRock25preList.size() > 0) {
            for(HddcRock25preEntity hddcRock25pre : hddcRock25preList) {
                hddcRock25pre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock25pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRock25pre.setIsValid("0");
                this.hddcRock25preRepository.save(hddcRock25pre);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public void exportFile(HddcRock25preQueryParams queryParams, HttpServletResponse response) {
        List<HddcRock25preEntity> yhDisasterEntities = hddcRock25preNativeRepository.exportYhDisasters(queryParams);
        List<HddcRock25preVO> list=new ArrayList<>();
        for (HddcRock25preEntity entity:yhDisasterEntities) {
            HddcRock25preVO yhDisasterVO=new HddcRock25preVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "1：25万工作底图岩体-面", "1：25万工作底图岩体-面", HddcRock25preVO.class, "1：25万工作底图岩体-面.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcRock25preVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRock25preVO.class, params);
            List<HddcRock25preVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcRock25preVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcRock25preVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcRock25preEntity> hddcRock25preList = this.hddcRock25preRepository.queryHddcRock25presByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcRock25preList) && hddcRock25preList.size() > 0) {
            for(HddcRock25preEntity hddcRock25pre : hddcRock25preList) {
                hddcRock25pre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock25pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRock25pre.setIsValid("0");
                this.hddcRock25preRepository.save(hddcRock25pre);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcRock25preEntity> hddcRock25preList = this.hddcRock25preRepository.queryHddcRock25presByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcRock25preList) && hddcRock25preList.size() > 0) {
            for(HddcRock25preEntity hddcRock25pre : hddcRock25preList) {
                hddcRock25pre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock25pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRock25pre.setIsValid("0");
                this.hddcRock25preRepository.save(hddcRock25pre);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("RockName")){
            str+="RockName,";
        }
        if(!set.contains("Symbol")){
            str+="Symbol,";
        }
        if(!set.contains("QDHO")){
            str+="QDHO,";
        }
        if(!set.contains("Description")){
            str+="Description,";
        }
        if(!set.contains("RockUnion")){
            str+="RockUnion,";
        }
        if(!set.contains("nsb1")){
            str+="nsb1,";
        }
        if(!set.contains("nsb2")){
            str+="nsb2,";
        }
        if(!set.contains("nsb3")){
            str+="nsb3,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void saveRock25preServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcRock25preEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcRock25preEntity data = new HddcRock25preEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setRockname(obs.get(2).toString());
                data.setSymbol(Integer.valueOf(obs.get(3).toString()));
                data.setQdho(Integer.valueOf(obs.get(4).toString()));
                data.setDescription(obs.get(5).toString());
                data.setRockunion(obs.get(6).toString());
                data.setNsb1(obs.get(7).toString());
                data.setNsb2(obs.get(8).toString());
                data.setNsb3(obs.get(9).toString());
                data.setCommentInfo(obs.get(10).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);

            saveHddcRock25preList(datas);
        }
    }

    @Override
    public List<HddcRock25preEntity> findAll() {
        List<HddcRock25preEntity> list=this.hddcRock25preRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {

        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcRock25preRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcRock25preEntity> hddcRock25preList = this.hddcRock25preRepository.queryHddcRock25presByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcRock25preList) && hddcRock25preList.size() > 0) {
            hddcRock25preRepository.deleteAll(hddcRock25preList);
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcRock25preVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcRock25preEntity yhDisasterEntity = new HddcRock25preEntity();
            HddcRock25preVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcRock25pre(yhDisasterEntity);
        }
    }

}
